package org.chen;

import org.chen.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Random;

@SpringBootApplication
public class MyShardingSphareJdbcDemoApplication {
    @Autowired
    private DataSource dataSource;

    public static void main(String[] args) {
        SpringApplication.run(MyShardingSphareJdbcDemoApplication.class, args);
    }

    //模拟10个用户创建订单过程
   /* @Bean
    public void shardingSphereConfigTest() throws SQLException {
        String sql = "INSERT INTO t_order (id,order_no,user_id,create_time) VALUES (?,?,?,?)";
        Connection conn = dataSource.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement pst = conn.prepareStatement(sql);
        for (int i = 0; i < 1000; i++) {
            String orderNo = StringUtil.getOrderNo("O", i);
            Integer userId = new Random(System.currentTimeMillis()).nextInt(10);
            Date createTime = new Date(new java.util.Date().getTime());
            pst.setInt(1, i);
            pst.setString(2, orderNo);
            pst.setInt(3, userId);
            pst.setDate(4, createTime);
            pst.addBatch();
        }
        pst.executeBatch();
        conn.commit();
    }*/

    @Bean
    public void shardingSphereTest() throws SQLException {
        String sql = "select * from t_order limit 0,10";
        Connection conn = dataSource.getConnection();
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        int colCount = resultSet.getMetaData().getColumnCount();
        for (int i = 1; i <= colCount; i++) {
            System.out.print(resultSet.getMetaData().getColumnLabel(i));
            System.out.print("\t");
        }
        System.out.println();
        while (resultSet.next()) {
            for (int i = 1; i <= colCount; i++) {
                System.out.print(resultSet.getObject(i));
                System.out.print("\t");
            }
            System.out.println();
        }
    }
}
